<script setup>
import { User, Lock, CircleCheck,Refresh,Message } from "@element-plus/icons-vue";
import { onMounted, ref,onUnmounted } from "vue";
import { ElNotification } from "element-plus";
import {setToken, getToken, removeToken } from '@/utils/auth/index'

const formModel = ref({
  uid: "",
  password: "",
  captcha: "",
});

const passModel = ref({
  uid: "",
  mail:"",
  newPassword: "",
  mailCode: "",
});
const rules = ref({
  uid: [
    {
      required: true,
      message: "输入用户名",
      trigger: "blur",
    },
    {
      min: 3, //记得改回6
      max: 16,
      message: "用户名长度在6-16位之间",
      trigger: "blur",
    },
  ],
  password: [
    //规则
    {
      //每个花括号一个
      required: true,
      message: "输入密码",
      trigger: "blur",
    },
    {
      pattern: /^\S{6,16}$/,
      message: "密码长度在6-16位之间的非空字符",
      trigger: "blur",
    },
  ],
  captcha: [
    {
      //每个花括号一个
      required: true,
      message: "输入验证码",
      trigger: "blur",
    },
  ],
});
const reset_rules = ref({
  uid: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
    {
      min: 10,
      max: 10,
      message: "用户名必须是10位数字",
      trigger: "blur",
    },
    {
      pattern: /^\d{10}$/,
      message: "用户名必须是10位数字",
      trigger: "blur",
    },
  ],
  mail: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      type: 'email',
      message: "邮箱格式不正确",
      trigger: "blur",
    }
  ],
  newPassword: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\S]{6,16}$/,
      message: "密码长度在6-16位之间，且必须包含大小写字母和数字",
      trigger: "blur",
    },
  ],
  mailCode: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
    {
      pattern: /^\d{6}$/,
      message: "验证码必须是6位数字",
      trigger: "blur",
    },
  ],
});

const form = ref();
const reset_form= ref();
const loading = ref(false);//这里就是防抖和节流，但是如果登录没成功，它将一直没办法继续向下


import { useUserStore } from "@/store";
import { useRoute, useRouter } from "vue-router"; //引入路由
//获取路由器
import router from "@/router";
//引入函数名就可以使用
let userStore = useUserStore();

//引入api接口
import {getcaptcha, userLoginService,getpassword,getmail} from "@/api/login";
import { en } from "element-plus/es/locales.mjs";

const captchaurl=ref("")

const token=ref('');
const beforeLogin=async()=>{
    const res = await getcaptcha();
    // console.log("rescha:",res);
    captchaurl.value = res.data.image;
    token.value = res.data.token;
}


onMounted(async () => {
  beforeLogin();

	window.addEventListener('keydown', keyDown)
});
onUnmounted(() => {
	//销毁事件
	window.removeEventListener('keydown', keyDown, false)
});
const Refreshcapt=async()=>{
  formModel.value.captcha=''
  beforeLogin();
}

const RefreshForm=async()=>{
  flg=!flg;
  formModel.value={}
  passModel.value={}
}

const Login = async () => {
  //登录
  await form.value.validate(); //必须校验
  // console.log("form:",formModel.value);
  const res = await userLoginService(formModel.value, token.value);
  // console.log("res:",res);
  if(res.code)
  {
    Refreshcapt()
    router.push("/login");
    return ;
  }
  // console.log("data: ",res.data)
  await userStore.userInfo(res.data);

  //登录成功后跳转到首页
  router.push("/");
  //还可跳转之前的页面
};

let flg=ref(true)//区分登录还是忘记密码

const mailtoken=ref('')
const btnCon=ref(1);//默认发送验证码
const getmailCode=async()=>{
    //还没补充,为什么禁用按钮会失效
  const res=await getmail(passModel.value.mail);
  mailtoken.value=res.mailToken;
  btnCon.value=2;
  //做一个倒计时
  let i=61;///一分钟
  const btn=document.querySelector(".mail_btn")
  //给按钮添加禁用
  let timer=setInterval(()=>{
    i--;
    btn.innerHTML=`重新发送(${i})`
    if(i==0)
    {
      btn.innerHTML='发送验证码'
      btnCon.value=1;
      clearInterval(timer);
    }
  },1000)
}

const ForgetPassword=async()=>{
  await reset_form.value.validate(); //必须校验
    const res = await getpassword(passModel.value,mailtoken.value);
    if(res.code)
    {
      passModel.value.mailCode='';
      ElNotification({
        title: '提示',
        message: "重置失败",
        type: 'error',
      });
      return;
    }
    
    ElNotification({
        title: '提示',
        message: "重置成功，请重新登录",
        type: 'success',
      });
    // window.location.reload()
    RefreshForm()
}

const keyDown = (e) => {
	if (e.keyCode == 13 || e.keyCode == 100) {
		Login()
	}
}
</script>
<template>
  <div class="login_container">
    <div v-if="flg" class="login_form">
      <el-form :model="formModel" :rules="rules" ref="form">
        <h1>欢迎！</h1>
        <h2>以科研创新为目标 以成才报国为己任</h2>
        <el-form-item prop="uid">
          <el-input
            v-model="formModel.uid"
            placeholder="请输入账号"
            :prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            type="password"
            show-password
          ></el-input>
          <show-password> </show-password>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captchas">
              <el-input
              v-model="formModel.captcha"
              placeholder="请输入验证码"
              :prefix-icon="CircleCheck"
            ></el-input>
            <div @click="Refreshcapt" style="height:35px;line-height: 35px;">
              <img :src="captchaurl" style="height:35px;"></img>
            </div>
            <!-- <Refresh @click="Refreshcapt" style="width:35px; height:35px; color: white;" /> -->
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="Login"
            style="width: 45%;margin-left: 3%;"
            @keydown.enter="keyDown()"
            >登录</el-button
          >
          <el-button
            @click="RefreshForm"
            style="width: 45%"
            >忘记密码</el-button
          >
          <!-- loading: 是否显示加载中，绑定了一个ref-->
        </el-form-item>
      </el-form>
      <!-- </el-card> -->
    </div>
    <div v-else class="login_form">
      <el-form :model="passModel" :rules="reset_rules" ref="reset_form">
        <h1>欢迎！</h1>
        <h2>以科研创新为目标 以成才报国为己任</h2>
         <el-form-item prop="uid">
          <el-input
            v-model="passModel.uid"
            placeholder="请输入账号"
            :prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mail">
          <el-input
            v-model="passModel.mail"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
          ></el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="passModel.newPassword"
            placeholder="请输入新密码"
            :prefix-icon="Lock"
            type="password"
            show-password
          ></el-input>
          <show-password> </show-password>
        </el-form-item>
        <el-form-item prop="mailCode">
          <div class="captchas">
             <el-input
              v-model="passModel.mailCode"
              placeholder="请输入邮箱验证码"
              :prefix-icon="CircleCheck"
            ></el-input>
            <el-button
            class="mail_btn"
            type="primary"
            @click="getmailCode"
            :disabled="passModel.mail?(btnCon==1?false:true):true"
            >发送验证码</el-button
          >
          </div>
            <!-- <Refresh @click="Refreshcapt" style="width:35px; height:35px; color: white;" /> -->
        </el-form-item>
      <el-form-item>
        <div class="captchas">
          <el-button
            type="success"
            @click="ForgetPassword"
            style="width: 90%;"
            >确认重置密码</el-button
          >
            <el-button
              link
              @click="RefreshForm"
            >返回</el-button>
        </div>
         
        </el-form-item>
      </el-form>
      <!-- </el-card> -->
    </div>
  </div>
</template>
<style lang="scss" scoped>
.login_container {
  width: 100%;
  height: 100%;
  //相对定位
  position: absolute;
  background: url("src/assets/images/bg1.png") no-repeat;
  background-size: cover;
  .login_form {
    position: absolute;
    width: 500px;
    left: 20%;
    top: 20%;
    background: url("@/assets/images/login_form.png") no-repeat;
    background-size: cover;
    padding: 40px; //内容距离盒子两边
    h1 {
      font-size: 40px;
      color: #fff;
    }
    h2 {
      font-size: 20px;
      color: #fff;
      margin: 20px 0px;
    }
  }
}
.captchas
{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
